package nettyTest.server;

import com.zyc.remoting.dto.RpcRequest;
import com.zyc.remoting.dto.RpcResponse;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import org.apache.zookeeper.server.ByteBufferOutputStream;

import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zyc
 * @create 2022--06--01 11:01
 */
public class NettyServerHandlerDemo extends ChannelInboundHandlerAdapter {
    private static final AtomicInteger atomicInteger = new AtomicInteger(1);
    /**
     * 数据读取
     * @param ctx 上下文对象
     * @param msg 接收到的数据
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
            RpcRequest rpcRequest = (RpcRequest) msg;
            System.out.println("服务器收到消息：" + rpcRequest.getInterfaceName() + "[" + atomicInteger.getAndIncrement() + "次]");
            RpcResponse<Object> response = RpcResponse.builder().message("来自服务器的消息").build();
            ChannelFuture f = ctx.writeAndFlush(response);
            f.addListener(ChannelFutureListener.CLOSE);
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }


    /**
     * 异常处理
     * @param channelHandlerContext
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable cause) {
        cause.printStackTrace();
        channelHandlerContext.close();
    }
}
